﻿using DataBase.Models;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeviceClientGrain;

namespace DeviceDemo
{
    /// <summary>
    /// 某道工序的解析线程
    /// </summary>
    internal class DemoAnalyseThread
    {
        bool running=false;
        private readonly IClusterClient client;

        public DemoAnalyseThread(IClusterClient clusterClient)
        {
            client=clusterClient;
        }

        /*
        async Task<IClusterClient> ConnectClient()
        { 
            IClusterClient  client = new ClientBuilder()
                 .UseLocalhostClustering()
                .AddSimpleMessageStreamProvider("DeviceProvider")
                .ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Error).AddConsole())
                .Build();

            await client.Connect(); 
            return client;
        }
        */

        public void Stop()
        {
            running = false;
        }
         
        public void Run( )
        {
            if (running) return;
            running = true;
             
            while (running)
            {
                DeviceReceiveData? data = DataQueue.Pop();
                if (data == null)
                {
                    //没有数据就休眠
                    Thread.Sleep(100);
                }
                else
                {
                    //有数据就解析
                    _ = 解析数据(data);
                } 
            }
            running = false;
        }

        Task 解析数据(DeviceReceiveData data)
        {
            //首先需要通过IP和Position 确定是哪个机台的入口 
            DemoDeviceInfo? device = DeviceMap.GetDetailDevice(data.IP, data.Position);
            if (device == null)
            {
                return Task.CompletedTask;
            } 
            var deviceGrain = client.GetGrain<IDeviceGroup>(device.Group);
            if (data.CmdType == DeviceReceiveType.物料信息)
            {
                _ = deviceGrain.更新物料数量(device.DeviceID, data.InNum, data.OutNum);

            }
            else if (data.CmdType == DeviceReceiveType.物料信息)
            {
                _ = deviceGrain.需要传输(device.DeviceID, data.NeedTrans);
            }
            else if (data.CmdType == DeviceReceiveType.通知AGV传输)
            {
                _ = deviceGrain.通知AGV传输(device.DeviceID, data.TransType);
            }
            else if (data.CmdType == DeviceReceiveType.通知AGV传输)
            {
                _ = deviceGrain.通知AGV离开(device.DeviceID);
            }
            return Task.CompletedTask;
        }
    }
}
